package com.example.managesystem.controller.Student;

import com.example.managesystem.constant.MessageConstant;
import com.example.managesystem.dto.FileDTO;
import com.example.managesystem.result.Result;
import com.example.managesystem.service.FileService;
import com.example.managesystem.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@CrossOrigin(origins = "*") //origins可以指定请求来源，*代表全部
@Api(tags = "通用接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private FileService fileService;


    @PostMapping("/upload")
    @ApiOperation(value = "上传附件")
    public Result upload(MultipartFile file, Integer item_id){
        log.info("文件上传：{}",file.getOriginalFilename());
        FileDTO fileDTO = new FileDTO();
        log.info("文件上传，itemId为：{}",item_id);
        fileDTO.setItemId(item_id);

        try {
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();

            //传入文件名称
            fileDTO.setFileName(originalFilename);

            //截取原始文件名的后缀 .jpg
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //传入文件后缀名
            fileDTO.setFormat(extension);

            //文件的请求路径
            String filepath = aliOssUtil.upload(file.getBytes(), originalFilename);
            //传入文件路径
            fileDTO.setFileUrl(filepath);
            fileService.saveFile(fileDTO);

            System.out.println(filepath);
            return Result.success(filepath);
        } catch (IOException e) {
            log.info("文件上传失败",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }
}
